import dialog from './dialog.js';
import app from '@/common/config/app.js'
import {
	upload
} from '@/api/common.js'
import {
	checkCameraPer,
	checkPhonePer,
	checkStoragePer
} from './permission.js';
import {
	finished
} from 'stream';
import store from "@/store";
import router from '@/common/utils/router.js';


const utils = {
	oss: null,
	dateFormat(fmt, date) {
		let ret;
		date = new Date(date);
		const opt = {
			"Y+": date.getFullYear().toString(), // 年
			"m+": (date.getMonth() + 1).toString(), // 月
			"d+": date.getDate().toString(), // 日
			"H+": date.getHours().toString(), // 时
			"M+": date.getMinutes().toString(), // 分
			"S+": date.getSeconds().toString() // 秒
			// 有其他格式化字符需求可以继续添加，必须转化成字符串
		};
		for (const k in opt) {
			ret = new RegExp("(" + k + ")").exec(fmt);
			if (ret) {
				fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
			};
		};
		return fmt;
	},
	formatDate(separator) {
		const year = new Date().getFullYear();

		let month = new Date().getMonth() + 1;
		if (month < 10) {
			month = '0' + month
		}
		let day = new Date().getDate();
		if (day < 10) {
			day = '0' + day
		}
		if (separator) {
			return `${year}${separator}${month}${separator}${day}`
		} else {

			return `${year}${month}${day}`;
		}
	},
	uuid(len, radix) {
		var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
		var uuid = [],
			i;
		radix = radix || chars.length;
		if (len) {
			for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
		} else {
			var r
			uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
			uuid[14] = '4'
			for (i = 0; i < 36; i++) {
				if (!uuid[i]) {
					r = 0 | Math.random() * 16
					uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
				}
			}
		}
		return new Date().getTime() + uuid.join('');
	},

	validatePhone(phone) {
		if (!/^1[3456789]\d{9}$/.test(phone)) {
			return false
		}
		return true
	},
	millisecondToTime(msd) {
		var time = parseInt(msd)
		if (time < 10) {
			time = '00:0' + time;

		} else if (time < 60) {
			time = '00:' + time;

		} else if (time >= 60 && time < 60 * 60) {
			let minutes = String(parseInt(time / 60));
			minutes = minutes.length === 2 ? minutes : '0' + minutes;
			let seconeds = String(time % 60);
			// console.log(seconeds.length)
			seconeds = seconeds.length === 2 ? seconeds : '0' + seconeds;
			time = minutes + ':' + seconeds
		} else {
			let hour = String(parseInt(time / 3600));
			hour = hour.length === 2 ? hour : '0' + hour;

			let minutes = String(parseInt(parseInt(time % 3600) / 60));
			minutes = minutes.length === 2 ? minutes : '0' + minutes;

			let seconeds = String(parseInt(parseInt(time % 3600) % 60));
			seconeds = seconeds.length === 2 ? seconeds : '0' + seconeds;
			time = hour + ':' + minutes + ':' + seconeds;

		}
		return time
	},
	compressImage(config) {
		if (typeof config !== 'object') {
			console.error('config cccept objects only');
			return
		}
		if (!config) {
			console.error('src is necessary');
			return
			config = {}
		}
		return new Promise((resolve, reject) => {
			uni.compressImage({
				...config,
				success: res => {
					resolve(res)
				},
				fail: err => {
					reject(err)
				}
			})
		})
	},
	setFileName(file) {
		let str =
			'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		let randomStr = '';
		for (let i = 17; i > 0; --i) {
			randomStr += str[Math.floor(Math.random() * str.length)];
		}

		let suffix = /\.\w+$/.exec(file.path)
		const name = new Date().getTime() + randomStr + suffix;
		return name
	},
	async chooseImage(config, onProgressUpdate) {
		// #ifdef APP
		try {
			await Promise.all([checkStoragePer(), checkCameraPer()])
			// checkStoragePer();
		} catch (e) {
			await dialog.confirm({
				nativeAlert: true,
				message: '学之家需要获取您的存储权限或者摄像头权限，方便您选择手机中的图片用于完善您的身份信息',
				confirmText: '确认允许'
			})
		}
		// #endif
		return new Promise(async (resolve, reject) => {
			if (!config) {
				config = {}
			}
			if (config.file) {
				let file = config.file;
				console.log(file)
				dialog.loading()
				upload({
					file: file,
					name: 'file'
				}).then(res => {
					console.log(res)
					dialog.hideLoading()
					resolve(res)
				}).catch(err => {
					dialog.hideLoading();
					console.log('err', err);
					utils.toast('上传失败' + err)
				})

			} else {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					crop: {
						quality: 10
					},
					sourceType: ['album', "camera"], //从相册选择
					success: async res => {
						console.log(res)
						let file = res.tempFiles[0];
						dialog.loading()
						if (!config.stopUpload) {
							upload({
								file: file,
								name: 'file',
								filePath: file.path,
							}).then(res => {
								console.log(res)
								dialog.hideLoading()
								resolve(res)
							}).catch(err => {
								console.log('err', err)
								dialog.hideLoading()
								utils.toast('上传失败,' + err.msg)
							})
						} else {
							resolve(res)
						}

					}
				})
			}
		})
	},
	chooseVideo(config, onProgressUpdate, uploadTask) {
		return new Promise((resolve, reject) => {

			uni.chooseVideo({
				maxDuration: 60,

				success: res => {
					if (res.tempFilePath.indexOf('.mp4') === -1) {
						dialog.alert('只能上传mp4格式的视频')
						return
					}
					console.log(res)
					if (!config) {
						config = {}
					}
					if (config.upload === false) {
						resolve(res)
					} else {
						dialog.loading()
						const data = {
							file: res.tempFilePath,
							name: 'file',
							filePath: res.tempFilePath
						}
						upload(data, onProgressUpdate, uploadTask).then(res => {
							console.log(res);
							dialog.hideLoading()
							resolve(res)
						}).catch((err) =>
							dialog.hideLoading()[
								reject(err)
							])
					}
				},
				fail: err => {
					reject(err)
				}
			})
		})
	},
	getLocation() {
		let location = {
			lat: 0,
			lng: 0,
		}
		return new Promise((resolve, reject) => { //因为获取位置是异步接口所以需要使用promise
			uni.getLocation({
				success(res) {
					console.log('getLocation', res);
					location.lat = res.latitude
					location.lng = res.longitude,
						store.commit('$CGStore', {
							name: '$position',
							value: location
						})
					resolve(location);
				},
				fail(err) {
					console.log('getLocation err:', err);
					reject(location); //获取失败则返回经纬坐标为0
				}
			})
		})
	},
	getDistance(start, end) {
		// /**
		//  * start :{lat: '',lng: ''}
		//  * end: {lat: '',lng: ''}
		//  */
		// console.log('计算地点经纬度：start', start);
		// console.log('计算地点经纬度：end', end);


		// // console.log('我的位置：', location);
		// let lat2 = end.lat;
		// let lng2 = end.lng;
		// let rad1 = start.lat * Math.PI / 180.0;
		// let rad2 = end.lat * Math.PI / 180.0;
		// let a = rad1 - rad2;
		// let b = start.lng * Math.PI / 180.0 - end.lng * Math.PI / 180.0;

		// let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(
		// 	rad2) * Math.pow(
		// 	Math.sin(b / 2), 2)));
		// s = s * 6378.137;
		// console.log()
		// s = Math.round(s * 10000) / 10000;
		// s = s.toString();
		// s = s.substring(0, s.indexOf('.') + 2);
		// console.log('距离：', s);
		// return s; //返回距离
		/**
		 * start :{lat: '',lng: ''}
		 * end: {lat: '',lng: ''}
		 */
		console.log('计算地点经纬度：start', start);
		console.log('计算地点经纬度：end', end);


		// console.log('我的位置：', location);
		let lat2 = end.lat.toFixed(3);
		let lng2 = end.lng.toFixed(3);
		let rad1 = start.lat.toFixed(3) * Math.PI / 180.0;
		let rad2 = end.lat.toFixed(3) * Math.PI / 180.0;
		let a = rad1 - rad2;
		let b = start.lng.toFixed(3) * Math.PI / 180.0 - end.lng.toFixed(3) * Math.PI / 180.0;

		let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(
			rad2) * Math.pow(
			Math.sin(b / 2), 2)));
		// s = s * 63781370;
		s = s * 6371393;
		console.log()
		s = Math.round(s * 10000) / 10000;
		s = s.toString();
		s = s.substring(0, s.indexOf('.') + 2);
		console.log('距离：', s);
		return s; //返回距离

	},
	previewImage(urls, current) {
		let url;
		if (!urls || urls.length === 0) {
			utils.alert('暂无图片信息')
			return
		}
		console.log(urls, urls.length)
		if (typeof urls === 'string') {
			url = [urls]
		} else {
			url = urls
		}
		uni.previewImage({
			urls: url,
			current: current || 0,
			complete(err) {
				console.log(err)
			}
		})
	},
	previewVideo(url) {
		router.push('/pages/common/video', {
			videourl: url
		})

	},
	isJSON(str) {
		if (typeof str == 'string') {
			try {
				JSON.parse(str)
				return true
			} catch (e) {
				return false
			}
		} else {
			return false
		}
	},
	paramsToObj(params) {
		const res = {

		}
		if (params.q) {
			//获取二维码的携带的链接信息
			let qrUrl = decodeURIComponent(params.q)
			console.log('qrcode', qrUrl)
			const obj = utils.getUrlParams(qrUrl)
			Object.keys(obj).forEach(key => {
				res[key] = utils.getQueryString(qrUrl, key)
			})


		} else if (params.scene) {
			console.log(params.scene)
			// 扫描schemec小程序码进入
			let qrUrl = '?' + decodeURIComponent(params.scene)
			console.log('schemec', qrUrl)
			const obj = utils.getUrlParams(qrUrl)
			Object.keys(obj).forEach(key => {
				res[key] = utils.getQueryString(qrUrl, key)
			})
		} else {
			Object.keys(params).forEach(key => {
				if (utils.isJSON(params[key])) {
					res[key] = JSON.parse(params[key])
				} else {

					res[key] = params[key]
				}
			})
		}
		Object.keys(res).forEach(item => {
			if (res[item] === 'null' || res[item] === 'undefined' || res[item] === undefined || res[
					item] === null) {
				res[item] = null
			}
		})
		return res;
	},
	beUrl(json) {

		return Object.keys(json).map(function(key) {
			if (typeof json[key] === 'object') {
				return key + "=" + JSON.stringify(json[key])
			} else {

				return key + "=" + json[key];
			}
		}).join("&");
	},
	chooseLocation(config) {
		if (!config) config = {};
		return new Promise((resolve, reject) => {
			uni.chooseLocation({
				success: res => {
					resolve(res)
				},
				fail: err => {
					reject(err)
				}
			})
		})
	},
	openLocation(config) {
		if (!config) config = {};

		return new Promise((resolve, reject) => {
			uni.openLocation({
				...config,
				success: res => {
					resolve(res)
				},
				fail: err => {
					reject(err)
				}
			})

		})
	},
	saveImageToPhotosAlbum(url, fileName) {
		return new Promise((resolve, reject) => {
			uni.authorize({
				scope: 'scope.writePhotosAlbum',
				success: auth => {
					uni.showLoading({
						title: 'loading...',
						mask: true
					})
					uni.saveImageToPhotosAlbum({
						filePath: url,
						success(res) {
							console.log(res)
							dialog.alert('文件已成功保存到相册').then(
								() => {
									resolve(res)

								})
						},
						fail(err) {
							reject(err)

							dialog.alert(
								'保存失败，请检查是否允许小程序保存图片到相册')
						}
					})

				},
				fail: err => {

					dialog.confirm({
						message: '您需要设置允许小程序保存到相册的权限',
						confirmText: '立即设置',
						cancelText: '暂不设置'
					}).then(() => {
						wx.openSetting({
							withSubscriptions: true,
							complete: e => {
								console.log(e)
							}
						})
					})
				}
			})
		})
	},
	canvasDraw(ctx, canvasId, _this) {
		return new Promise((resolve, reject) => {
			// 执行绘制
			ctx.draw(false, () => {
				// 绘制完成后，将 canvas 转换为图片
				uni.canvasToTempFilePath({
					canvasId: canvasId,
					success: (res) => {
						resolve(res.tempFilePath)
					},
					fail: (err) => {
						console.error('转换失败', err);
						reject(err)
					}
				}, _this);
			});
		})

	},
	openFile(url) {
		if (!url) {
			dialog.alert("暂无文件信息")
			return
		}
		if (isImageUrl(url)) {
			utils.previewImage(url)
		} else {

			uni.showLoading({
				title: '正在打开文件...',
				mask: true
			})
			uni.downloadFile({
				url: url,
				success: function(res) {
					console.log(res)
					var filePath = res.tempFilePath;
					uni.openDocument({
						filePath: filePath,
						// showMenu: true,
						success: function(res) {
							console.log('打开文档成功');
						},
						complete(e) {
							uni.hideLoading()
							console.log(e)
						},
						fail(e) {
							console.log(1222, e)
							dialog.alert("暫不支持打开此类型文档")
						}
					});
				},
				complete(e) {
					console.log(e);
					uni.hideLoading()
				},
				fail(e) {
					console.log(111, e);
					uni.hideLoading()
					dialog.alert(e.errMsg)
				}
			});
		}
	},
	downloadFile(url) {
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url: url,
				success: function(res) {
					resolve(res.tempFilePath);
				},
				fail: function(err) {
					console.log(err)
					reject(err)
				}
			});
		})
	
	},
	getImageInfo(src) {
		return new Promise((resolve, reject) => {
			uni.getImageInfo({
				src: src,
				success: res => {
					resolve(res)
				},
				fail: err => {
					console.log('getImageInfo ERR:', err)
					reject(err)
				}
			})
		})
	},
	isImageFile(item) {
		console.log(item)
		if (item.isImage != null) {
			return item.isImage;
		}
		if (item.type) {
			return item.type === 'image';
		}
		if (item.url) {
			return isImageUrl(item.url);
		}
		return false;
	},
	pay(params) {
		return new Promise((resolve, reject) => {
			// #ifdef APP-PLUS
			const data = {
				orderInfo: {

					// appid:params.appId,
					appid: 'wxe510241b0669a8ad',
					noncestr: params.nonceStr,
					package: params.packageValue,
					partnerid: params.partnerId,
					prepayid: params.prepayId,
					timestamp: Number(params.timeStamp),
					sign: params.sign

				}
			}
			// #endif
			// #ifdef MP-WEIXIN
			const data = {
				...params,
				package: params.packageValue,
			}
			// #endif
			console.log('data', data);
			uni.requestPayment({
				provider: 'wxpay',
				...data,
				success: e => {
					resolve(e)
				},
				fail: err => {
					console.log('err', err);
					reject(err)
				}
			})
		})
	},
	copyText(text) {
		uni.setClipboardData({
			data: text,
			showToast: false,
			success: (e) => {
				dialog.toast('复制成功')
				console.log(e)
			}
		})
	},
	scanCode() {
		return new Promise((resolve, reject) => {
			uni.scanCode({
				success: res => {
					console.log('scan result:', res)
					resolve(res)
				},
				fail: err => {
					reject(err)
				}
			})
		})
	},
	getWeek() {
		var tempDate = new Date();

		var days = tempDate.getDay();
		var week;

		switch (days) {
			case 1:
				week = '星期一';
				break;
			case 2:
				week = '星期二';
				break;
			case 3:
				week = '星期三';
				break;
			case 4:
				week = '星期四';
				break;
			case 5:
				week = '星期五';
				break;
			case 6:
				week = '星期六';
				break;
			case 0:
				week = '星期日';
				break;
		}
		return week
	},
	exportFile(url, fileName = "") {
		const link = document.createElement('a'); // 创建a标签
		link.href = url;
		link.target = '__blank'
		//   link.download = fileName; // 重命名文件
		link.click();
	},
	isImageFile(item) {
		console.log('item', item);
		if (item.isImage != null) {
			return item.isImage;
		}
		if (item.type) {
			return item.type === 'image';
		}
		if (item.url) {
			console.log('item.url', item.url);
			return isImageUrl(item.url);
		}
		return isImageUrl(item);
	},
	isVideoFile(item) {
		if (item.isVideo != null) {
			return item.isVideo;
		}
		if (item.type) {
			return item.type === 'video';
		}
		if (item.url) {
			return isVideoUrl(item.url);
		}
		return isVideoUrl(item);
	},
	setTitle(title) {
		let config = {};
		typeof title === 'string' ? config.title = title : config = title;
		uni.setNavigationBarTitle({
			...config
		})
	},
	isMobile() {
		const systemInfo = uni.getSystemInfoSync()
		console.log(systemInfo)
		if (systemInfo.platform.indexOf('android') !== -1 || systemInfo.platform.indexOf('ios') !== -1) {
			return true
		}
		return false
	},
	async makePhone(phone) {
		// #ifdef APP
		try {
			await checkPhonePer();
		} catch (e) {
			await dialog.confirm({
				nativeAlert: true,
				message: '学之家需要获取您的拨打电话权限，用于一键报警功能',
				confirmText: '确认允许'
			})
		}
		// #endif

		// console.log('2', 2);
		if (utils.isMobile()) {
			uni.makePhoneCall({
				phoneNumber: phone, //仅为示例
				complete(e) {
					console.log(e)
				}
			});
		} else {
			dialog.alert(String(phone))
		}
	},
	checkUpdateVersion(showAlert) {
		//判断微信版本是否 兼容小程序更新机制API的使用
		if (uni.canIUse('getUpdateManager')) {
			//创建 UpdateManager 实例
			const updateManager = uni.getUpdateManager();
			// console.log(updateManager)
			//检测版本更新
			updateManager.onCheckForUpdate(function(res) {
				// 请求完新版本信息的回调
				console.log(res)
				if (res.hasUpdate) {
					//监听小程序有版本更新事件
					updateManager.onUpdateReady(function() {
						//TODO 新的版本已经下载好，调用 applyUpdate 应用新版本并重启 （ 此处进行了自动更新操作）
						dialog.alert({
							title: '更新提示',
							message: '新版本已经准备好，请重启应用',
						}).then(() => {
							updateManager.applyUpdate()
						}).catch(() => {
							updateManager.applyUpdate()
						})
					})
					updateManager.onUpdateFailed(function() {
						// 新版本下载失败
						dialog.alert({
							title: '已经有新版本',
							message: '请您删除当前小程序，到微信 “发现-小程序” 页，重新搜索打开哦~',
						})
						// uni.showModal({
						// 	title: '已经有新版本喽~',
						// 	content: '请您删除当前小程序，到微信 “发现-小程序” 页，重新搜索打开哦~',
						// })
					})
				} else {
					if (showAlert) {
						dialog.alert({
							title: '溫馨提示',
							message: '当前已是最新版本',
						})
					}
				}
			})
		} else {
			//TODO 此时微信版本太低（一般而言版本都是支持的）
			dialog.alert({
				title: '溫馨提示',
				message: '当前微信版本过低，部分功能受限，请升级到最新微信版本后重试。',
			})
			// uni.showModal({
			// 	title: '溫馨提示',
			// 	content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
			// })
		}
	},
	/**
	 * 判断是否为空
	 * @param {*} object 源对象
	 */
	isEmpty(value) {
		if (utils.isArray(value)) {
			return value.length === 0
		}
		if (utils.isObject(value)) {
			return utils.isEmptyObject(value)
		}
		return !value
	},
	/**
	 * 判断是否为空对象
	 * @param {*} object 源对象
	 */
	isEmptyObject(object) {
		return Object.keys(object).length === 0
	},
	/**
	 * 判断是否为对象
	 * @param {*} object
	 */
	isObject(object) {
		return Object.prototype.toString.call(object) === '[object Object]'
	},

	/**
	 * 判断是否为数组
	 * @param {*} array
	 */
	isArray(array) {
		return Object.prototype.toString.call(array) === '[object Array]'
	},

	/**
	 * 判断是否为空
	 * @param {*} object 源对象
	 */
	isEmpty(value) {
		if (utils.isArray(value)) {
			return value.length === 0
		}
		if (utils.isObject(value)) {
			return utils.isEmptyObject(value)
		}
		return !value
	},
	getList(request, params) {
		return new Promise(async (resolve, reject) => {
			params = params || {};
			const limit = app.pageSize || params.limit;
			const page = params.page || 1;
			let loadingStatus = params.loadingStatus || 'loading';
			try {
				const {
					data
				} = await request({
					offset: (page - 1) * limit,
					limit: limit,
					...params
				})
				if (data.results?.length < limit) {
					loadingStatus = 'finished';
				}
				if (page === 1 && data.results.length === 0) {
					loadingStatus = 'empty'
				}
				resolve({
					data,
					limit,
					page,
					loadingStatus

				})
			} catch (err) {
				reject(err)
			}

		})
	},
	getLiveInfo(config) {
		return new Promise((resolve, reject) => {

			uni.getChannelsLiveInfo({
				finderUserName: app.liveVideoId,
				...config,
				success: res => {
					resolve(res)
				},
				fail: err => {
					reject(err)
				}
			})
		})
	},
	refresh(pagePath, funcName, params) {
		/* this.$utils.refresh('/pages/index/index', 'getData', 124) */
		const pages = getCurrentPages()
		const targetPage = pages.find(page => ('/' + page.route) === pagePath)
		if (targetPage) {
			targetPage[funcName]?.call(this, params) // 直接调用目标页面的方法
		} else {
			console.log('page is not init');
		}
	}
}

const IMAGE_REGEXP = /\.(jpeg|jpg|gif|png|svg|webp|jfif|bmp|dpg)/i;
const VIDEO_REGEXP = /\.(mp4|mpg|mpeg|dat|asf|avi|rm|rmvb|mov|wmv|flv|mkv)/i;

export function isImageUrl(url) {
	return IMAGE_REGEXP.test(url);
}
export function isVideoUrl(url) {
	return VIDEO_REGEXP.test(url);
}
export default utils;